package com.example.myapplication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class MyService extends Service {

    private final String TAG = "MyService";
    private boolean mServiceRunning = false;
    private int mSecond = 0;

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate 被调用");
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind 被调用");
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand 被调用");
        new Thread(() -> {
            mServiceRunning = true;
            while (mServiceRunning) {
                Log.d(TAG, "新线程已经被运行了" + mSecond + "秒");
                try {
                    Thread.sleep(1000);
                    mSecond++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy 被调用");
        mServiceRunning = false;
        super.onDestroy();
    }

}
